package com.gccloud.tgyfirst.service.demo.service.impl;

import com.gccloud.tgyfirst.service.demo.dao.StudentCourseDao;
import com.gccloud.tgyfirst.demo.entity.CourseEntity;
import com.gccloud.tgyfirst.demo.entity.StudentCourseEntity;
import com.gccloud.tgyfirst.service.demo.service.ICourseService;
import com.gccloud.tgyfirst.service.demo.service.IStudentCourseService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.core.shiro.SysUser;
import com.gccloud.starter.core.shiro.UserUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author qianxing
 * @version 1.0
 * @date 2021/5/17 15:21
 */
@Service
public class StudentCourseServiceImpl extends ServiceImpl<StudentCourseDao, StudentCourseEntity> implements IStudentCourseService {
    @Lazy
    @Resource
    ICourseService courseService;

    @Override
    public void select(StudentCourseEntity studentCourseEntity) {

        SysUser currentUser = UserUtils.getCurrentUser(false);
        String studentId = currentUser.getId();
        studentCourseEntity.setStudentId(studentId);
        // 检查是否已选
        LambdaQueryWrapper<StudentCourseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourseEntity::getCourseId, studentCourseEntity.getCourseId());
        queryWrapper.eq(StudentCourseEntity::getStudentId, studentId);

        if (count(queryWrapper) > 0){
            throw new GlobalException("您已选择过该课程", 310);
        }
        // 检查选课时间
        CourseEntity courseEntity = courseService.getById(studentCourseEntity.getCourseId());
        if (courseEntity != null){
            Date startDate = courseEntity.getStartDate();
            Date nowDate = new Date();
            if (nowDate.after(startDate)){
                /**
                 * 自定义抛出异常，并指定接口返回码，以便前端根据返回码自定义处理业务需求
                 */
                throw new GlobalException("课程选课时间已过", 300);
            }
            this.save(studentCourseEntity);
        }
    }


    @Override
    public void cancelSelect(String courseId){
        SysUser currentUser = UserUtils.getCurrentUser(false);
        String studentId = currentUser.getId();
        LambdaQueryWrapper<StudentCourseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourseEntity::getCourseId, courseId);
        queryWrapper.eq(StudentCourseEntity::getStudentId, studentId);
        this.delete(queryWrapper);
    }
}
